package com.bridgetree.jubaocrm.ui;

import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.project.XMChildActivity;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Projects;

/**
 * 项目适配器
 * 
 */
public class PageProjectAdapter extends BaseAdapter {
	private List<Projects> Date = null;
	private Context context;
	private LayoutInflater mInflater;
	public HashMap<Integer, Bitmap> cachedBitmap;

	private class GridHolder {
		TextView tv;
	}

	@SuppressLint("UseSparseArrays")
	public PageProjectAdapter(Context c, List<Projects> proInfoListData) {
		super();
		this.context = c;
		this.Date = proInfoListData;
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public int getCount() {
		if(Date==null){
			return 0;
		}else{
			return Date.size();
		}
		
	}

	@Override
	public Object getItem(int index) {
		return Date.get(index);
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	@Override
	public View getView(final int index, View convertView, ViewGroup parent) {
		GridHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.xm_12_item, null);
			holder = new GridHolder();
			holder.tv = (TextView) convertView.findViewById(R.id.xm_12_item_tv);
			convertView.setTag(holder);
		} else {
			holder = (GridHolder) convertView.getTag();
		}

		final String xm_txt = Date.get(index).getProject_name();
		holder.tv.setText(xm_txt);
		convertView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getBasicInfomation(Date.get(index));
			}
		});
		return convertView;
	}

	private void openDailog(String title, final String content, Context mContext) {
		new AlertDialog.Builder(mContext).setTitle(title).setMessage(content)
				.setPositiveButton("确定",  new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						if (content != null && content.trim().equals("用户不存在")) {
							// finish();
						}
						if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
							LoginUtil.executeLoginFaild(context);
						}

					}
				}).show();
	}

	/**
	 * 获取基本信息
	 */
	private void getBasicInfomation(final Projects mProjects) {
		Network mNetword = new Network(context);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！", context);
		} else {
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
			String user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
			String token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, ""); 
			String URL = Network.API_DOMAIN+"/base_info_of_project?project_id="
					+ mProjects.getProject_id()
					+ "&user_id="
					+ user_id
					+ "&token="
					+ token
					+ "&validation="
					+ CRMUserBaseInfo.kValication
					+ "&part=home";
			
			final ProgressDialog progressDialog = ProgressDialog.show(context,
					"网络数据", "...Loading...");
			RequestQueue requestQueue = Volley.newRequestQueue(context);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
					Request.Method.GET, URL, null,
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							Log.d("JSONObject", "response:" + response);
							try {
								// System.out.println("response="+response);
								if (progressDialog.isShowing()
										&& progressDialog != null) {
									progressDialog.dismiss();
								}
								if(response.isNull("errors") || response.get("errors")
										.toString().equals("[]")){
									//获取营销审核状态
									String process_status = response.get(
											"process_status").toString();
									Intent intent = new Intent(context,
											XMChildActivity.class);
									mProjects.setProcess_status(process_status);
									if (!response.isNull("is_user_in_this_project")) {
										String is_user_in_this_project = response
												.getString("is_user_in_this_project");
										mProjects.setIs_user_in_this_project(Boolean.parseBoolean(is_user_in_this_project));
									}
									if (!response.isNull("is_final_approve")) {
										String is_final_approve = response
												.getString("is_final_approve");
										mProjects.setIs_final_approve(Boolean.parseBoolean(is_final_approve));
									}
									if (!response.isNull("is_approve_project")) {
										String is_approve_project = response
												.getString("is_approve_project");
										mProjects.setIs_approve_project(Boolean.parseBoolean(is_approve_project));
										
									}
									if (!response.isNull("is_creater")) {
										String is_creater = response
												.getString("is_creater");
										mProjects.setIs_creater(Boolean.parseBoolean(is_creater));
									}
									if (!response.isNull("flag_only_view_base_info")) {
										String flag_only_view_base_info = response
												.getString("flag_only_view_base_info");
										mProjects.setFlag_only_view_base_info(Boolean.parseBoolean(flag_only_view_base_info));
									}
									if (!response.isNull("is_edit_project")) {
										String is_edit_project = response
												.getString("is_edit_project");
										mProjects.setIs_edit_project(Boolean.parseBoolean(is_edit_project));
									}
									if (!response.isNull("approved_date")) {
										String approved_date = response
												.getString("approved_date");
										mProjects.setApproved_date(approved_date);
									}
									if (!response.isNull("approved_by")) {
										String approved_by = response
												.getString("approved_by");
										mProjects.setApproved_by(approved_by);
									}
									if (!response.isNull("is_view_all_projects_or_reviewers")) {
										String is_view_all_projects_or_reviewers = response
												.getString("is_view_all_projects_or_reviewers");
										mProjects.setIs_view_all_projects_or_reviewers(Boolean
														.parseBoolean(is_view_all_projects_or_reviewers));
									}
									Bundle bundle = new Bundle();
									bundle.putSerializable("my_projects", mProjects);
									intent.putExtras(bundle);
									((Activity) context).startActivityForResult(
											intent, 10001);

								}else{
									String errors = response.get("errors")
											.toString();
									if (errors.equals("[]")) {
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
													.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
														.length(); i++) {
													JSONObject jsonObj2 = jsonArr
															.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
																.getString("desc");
														openDailog("失败提示",
																desc, context);
														mLoginError
																.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
																.getString("value");
														mLoginError
																.setValue(value);
													}
												}
											}
										}
									}
								}

							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError arg0) {
							if (progressDialog.isShowing()
									&& progressDialog != null) {
								progressDialog.dismiss();
							}
							System.out.println("sorry,Error");
						}
					});
			requestQueue.add(jsonObjectRequest);
		}
	}
}
